package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"gopkg.in/gomail.v2"
	"yunshangxiaozhao/utils"
)

type EmailController struct {
	beego.Controller
}

func (e *EmailController) RetData(resp map[string]interface{}) {
	resp["code"] = 200
	e.Data["json"] = resp
	e.ServeJSON()
}

// @Title SendVerifyEmail
// @Description send verify email to prove email address
// @Success 200 {int} models.User.Id
// @Failure 400 body is empty
// @router /sendVerifyEmail [post]
func (e *EmailController) SendVerifyEmail() {
	resp := make(map[string]interface{})
	req := make(map[string]interface{})
	_ = json.Unmarshal(e.Ctx.Input.RequestBody, &req)
	defer e.RetData(resp)
	toEmail := req["toEmail"].(string)

	m := gomail.NewMessage()
	m.SetHeader("From", "TheKernelZ@163.com")
	m.SetHeader("To", toEmail)
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/html", "您好, 您的验证码为: <b>"+utils.GenerateVerifyCode()+"</b>!")

	d := gomail.NewDialer("smtp.163.com", 465, "TheKernelZ@163.com", "Kernel990621")

	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
	resp["code"] = 200
	resp["msg"] = "发送验证邮件成功"
	resp["data"] = nil
}
